package com.iring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.iring.exception.AuthenticationException;


/**
 * 拦截请求头XAuthToken
 *
 * @author wanggan
 */
@Configuration
public class AuthTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 如果是options请求是cors跨域预请求，设置allow对应头信息
        if (RequestMethod.OPTIONS.toString()
                .equals(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
//            response.setHeader("Access-Control-Allow-Headers", "XAuthToken");
            response.setHeader("Access-Control-Allow-Headers", "*");
            return true;
        }
        // 其他请求获取头信息
        final String authHeader = request.getHeader("XAuthToken");
        // 如果没有header信息
        if (authHeader == null || "".equals(authHeader.trim())) {
            throw new AuthenticationException("Missing or invalid XAuthToken header.");
        }
        return Boolean.TRUE;
    }
}
